﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bigger.Web.Mvc;
using Bigger.Framework;
using CJAtech.BBS.DataEntity;
using System.Web.Mvc;
using Bigger.Web.Helper;

namespace CJAtech.BBS.Process
{
    public class BBSCorsFilter : BiggerResultFilter, IExceptionFilter
    {
        /// <summary>
        /// 是否允许跨域
        /// </summary>
        public bool AllowCrossDomain { get; set; }
        public BBSCorsFilter()
        {
            this.AllowCrossDomain = true;
        }
        public override void OnResultExecuting(System.Web.Mvc.ResultExecutingContext filterContext)
        {
            this.EnableCors(filterContext);
        }

        public void OnException(ExceptionContext filterContext)
        {
            this.EnableCors(filterContext);
        }

        private void EnableCors(ControllerContext filterContext)
        {
            if (!this.AllowCrossDomain)
            {
                return;
            }
            var objCommunityConfig = filterContext.HttpContext.GetItems("CommunityConfig") as CommunityConfig;
            if (objCommunityConfig == null)
            {
                return;
            }
            if (objCommunityConfig.AllowOrigins.IsNull())
            {
                return;
            }

            //todo：匿名登录
            string[] allowOrigins = objCommunityConfig.AllowOrigins.Split('|');
            HttpRequestBase request = filterContext.HttpContext.Request;
            string[] origins = request.Headers.GetValues("Origin");
            string origin = origins.IsNoNull() ? origins.FirstOrDefault() : null;
            if (origin.IsNull())
            {
                return;
            }
            origin = origin.ToLower();
            HttpResponseBase response = filterContext.HttpContext.Response;
            if (allowOrigins.Contains("*") || allowOrigins.Contains(origin))
            {
                //设置响应报头"Access-Control-Allow-Methods"
                response.Headers.Add("Access-Control-Allow-Origin", origin);

                if (IsPreflightRequest(request))
                {
                    //设置响应报头"Access-Control-Request-Headers"
                    //和"Access-Control-Allow-Headers"
                    response.Headers.Add("Access-Control-Allow-Methods", "*");
                    string requestHeaders = request.Headers.GetValues("Access-Control-Request-Headers").FirstOrDefault();
                    if (!string.IsNullOrEmpty(requestHeaders))
                    {
                        response.Headers.Add("Access-Control-Allow-Headers", requestHeaders);
                    }
                }
            }
        }

        /// <summary>
        /// 浏览器预检查的条件
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private bool IsPreflightRequest(HttpRequestBase request)
        {
            return string.Equals(request.HttpMethod, "Options", StringComparison.OrdinalIgnoreCase) &&
                request.Headers.GetValues("Origin").Any() &&
                request.Headers.GetValues("Access-Control-Request-Method").Any();
        }
    }
}